<template>
  <div class="chapter-manager">
    <h3 class="chapter-manager-title">章节管理</h3>
    
    <!-- 章节列表 -->
    <div class="chapters-container">
      <div v-for="(chapter, chapterIndex) in chapters" :key="chapter.id" class="chapter-item">
        <!-- 章节头部 -->
        <div class="chapter-header">
          <div class="chapter-info">
            <el-input
              v-model="chapter.name"
              placeholder="章节标题"
              size="small"
              class="chapter-name-input"
              @blur="updateChapterName(chapterIndex)"
            />
            <span class="chapter-duration">{{ getChapterDuration(chapter) }}</span>
          </div>
          <div class="chapter-actions">
            <el-button type="primary" size="small" @click="addSection(chapterIndex)">
              <el-icon><Plus /></el-icon> 添加小节
            </el-button>
            <el-button size="small" @click="deleteChapter(chapterIndex)">
              <el-icon><Delete /></el-icon> 删除章节
            </el-button>
          </div>
        </div>
        
        <!-- 小节列表 -->
        <div class="sections-container">
          <div
            v-for="(section, sectionIndex) in chapter.sections"
            :key="section.id"
            class="section-item"
          >
            <div class="section-info">
              <div class="section-type">
                <el-select
                  v-model="section.type"
                  size="small"
                  class="section-type-select"
                  @change="updateSection(sectionIndex, chapterIndex)"
                >
                  <el-option label="视频" value="video"></el-option>
                  <el-option label="文档" value="document"></el-option>
                </el-select>
              </div>
              <el-input
                v-model="section.name"
                placeholder="小节标题"
                size="small"
                class="section-name-input"
                @blur="updateSection(sectionIndex, chapterIndex)"
              />
              
              <!-- 视频上传区域 -->
              <div v-if="section.type === 'video'" class="section-video">
                <el-upload
                  class="video-uploader"
                  :action="'/api/upload/video'"
                  :show-file-list="false"
                  :on-success="(response) => handleVideoUpload(response, sectionIndex, chapterIndex)"
                  :before-upload="beforeVideoUpload"
                >
                  <el-button size="small" :disabled="!!section.url">
                    <el-icon><Upload /></el-icon>
                    {{ section.url ? '重新上传' : '上传视频' }}
                  </el-button>
                </el-upload>
                <el-input
                  v-model="section.duration"
                  placeholder="时长 (HH:MM:SS)"
                  size="small"
                  class="duration-input"
                  @blur="updateSection(sectionIndex, chapterIndex)"
                />
                <el-switch
                  v-model="section.isPreview"
                  inline-prompt
                  active-text="可预览"
                  inactive-text="需购买"
                  @change="updateSection(sectionIndex, chapterIndex)"
                />
              </div>

              <!-- 文档上传区域 -->
              <div v-else class="section-document">
                <el-upload
                  class="document-uploader"
                  :action="'/api/upload/document'"
                  :show-file-list="false"
                  :on-success="(response) => handleDocumentUpload(response, sectionIndex, chapterIndex)"
                >
                  <el-button size="small" :disabled="!!section.url">
                    <el-icon><Upload /></el-icon>
                    {{ section.url ? '重新上传' : '上传文档' }}
                  </el-button>
                </el-upload>
              </div>

              <!-- 已上传的媒体预览 -->
              <div v-if="section.url" class="media-preview">
                <div v-if="section.type === 'video'" class="video-preview">
                  <video :src="section.url" controls class="preview-video">您的浏览器不支持视频播放</video>
                </div>
                <div v-else class="document-preview">
                  <el-link :href="section.url" target="_blank">
                    <el-icon><Document /></el-icon> 查看文档
                  </el-link>
                </div>
              </div>
            </div>
            
            <div class="section-actions">
              <el-button size="small" @click="moveSection(sectionIndex, chapterIndex, -1)" :disabled="sectionIndex === 0">
                <el-icon><ArrowUp /></el-icon> 上移
              </el-button>
              <el-button size="small" @click="moveSection(sectionIndex, chapterIndex, 1)" :disabled="sectionIndex === chapter.sections.length - 1">
                <el-icon><ArrowDown /></el-icon> 下移
              </el-button>
              <el-button size="small" type="danger" @click="deleteSection(sectionIndex, chapterIndex)">
                <el-icon><Delete /></el-icon> 删除
              </el-button>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 添加章节按钮 -->
    <div class="add-chapter-container">
      <el-button type="primary" @click="addChapter">
        <el-icon><Plus /></el-icon> 添加章节
      </el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, watch,onMounted } from 'vue'
import { Plus, Delete, Upload, Document, ArrowUp, ArrowDown } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import {coursesById} from "@/api/Course.js";
// 定义props
const props = defineProps({
  courseId: {
    type: [String, Number],
    required: true
  },
  initialChapters: {
    type: Array,
    default: () => []
  }
})

// 定义emit
const emit = defineEmits(['update:chapters'])

// 章节数据
let chapters = reactive([])

// 监听章节变化，同步到父组件
watch(() => [...chapters], (newChapters) => {
  emit('update:chapters', newChapters)
}, { deep: true })
//通过课程id查询课程详细信息
const getCourse=()=>{
  coursesById(props.courseId).then(res=>{
    chapters=res.data
    console.log("查询课程详情后的信息....")
    console.log(chapters)
  })
}
onMounted(()=>{
  getCourse()
})
// 添加章节
const addChapter = () => {
  const newChapter = {
    id: Date.now(),
    name: `第${chapters.length + 1}章：新章节`,
    sections: []
  }
  chapters.push(newChapter)
  ElMessage.success('章节添加成功')
}

// 删除章节
const deleteChapter = (index) => {
  if (chapters.length <= 1) {
    ElMessage.warning('至少保留一个章节')
    return
  }
  chapters.splice(index, 1)
  ElMessage.success('章节删除成功')
}

// 更新章节名称
const updateChapterName = (index) => {
  ElMessage.success('章节名称更新成功')
}

// 添加小节
const addSection = (chapterIndex) => {
  const chapter = chapters[chapterIndex]
  const newSection = {
    id: Date.now(),
    name: `${chapterIndex + 1}.${chapter.sections.length + 1} 新小节`,
    type: 'video',
    url: '',
    duration: '00:00',
    isPreview: false
  }
  chapter.sections.push(newSection)
  ElMessage.success('小节添加成功')
}

// 删除小节
const deleteSection = (sectionIndex, chapterIndex) => {
  const chapter = chapters[chapterIndex]
  if (chapter.sections.length <= 1) {
    ElMessage.warning('每个章节至少保留一个小节')
    return
  }
  chapter.sections.splice(sectionIndex, 1)
  ElMessage.success('小节删除成功')
}

// 更新小节信息
const updateSection = (sectionIndex, chapterIndex) => {
  ElMessage.success('小节信息更新成功')
}

// 移动小节
const moveSection = (sectionIndex, chapterIndex, direction) => {
  const chapter = chapters[chapterIndex]
  const newIndex = sectionIndex + direction
  
  if (newIndex < 0 || newIndex >= chapter.sections.length) {
    return
  }
  
  // 交换位置
  const temp = chapter.sections[sectionIndex]
  chapter.sections[sectionIndex] = chapter.sections[newIndex]
  chapter.sections[newIndex] = temp
  
  ElMessage.success('小节位置已调整')
}

// 处理视频上传
const handleVideoUpload = (response, sectionIndex, chapterIndex) => {
  const section = chapters[chapterIndex].sections[sectionIndex]
  // 模拟上传成功响应
  section.url = response.url || URL.createObjectURL(response.raw)
  ElMessage.success('视频上传成功')
}

// 处理文档上传
const handleDocumentUpload = (response, sectionIndex, chapterIndex) => {
  const section = chapters[chapterIndex].sections[sectionIndex]
  // 模拟上传成功响应
  section.url = response.url || URL.createObjectURL(response.raw)
  ElMessage.success('文档上传成功')
}

// 视频上传前校验
const beforeVideoUpload = (file) => {
  const isMP4 = file.type === 'video/mp4' || file.type === 'video/webm'
  const isLt200M = file.size / 1024 / 1024 < 200

  if (!isMP4) {
    ElMessage.error('上传视频只能是 MP4/WebM 格式!')
  }
  if (!isLt200M) {
    ElMessage.error('上传视频大小不能超过 200MB!')
  }
  return isMP4 && isLt200M
}

// 计算章节总时长
const getChapterDuration = (chapter) => {
  if (!chapter.sections || chapter.sections.length === 0) {
    return '00:00'
  }
  
  let totalSeconds = 0
  
  chapter.sections.forEach(section => {
    if (section.type === 'video' && section.duration) {
      try {
        const parts = section.duration.split(':').map(Number)
        
        // 处理不同格式的时长：HH:MM:SS 或 MM:SS
        if (parts.length === 3) {
          const [hours, minutes, seconds] = parts
          // 确保所有值都是有效数字
          if (!isNaN(hours) && !isNaN(minutes) && !isNaN(seconds)) {
            totalSeconds += hours * 3600 + minutes * 60 + seconds
          }
        } else if (parts.length === 2) {
          const [minutes, seconds] = parts
          // 确保所有值都是有效数字
          if (!isNaN(minutes) && !isNaN(seconds)) {
            totalSeconds += minutes * 60 + seconds
          }
        }
      } catch (error) {
        console.log('解析时长出错:', error)
      }
    }
  })
  
  const hours = Math.floor(totalSeconds / 3600).toString().padStart(2, '0')
  const minutes = Math.floor((totalSeconds % 3600) / 60).toString().padStart(2, '0')
  const seconds = (totalSeconds % 60).toString().padStart(2, '0')
  
  return `${hours}:${minutes}:${seconds}`
}
</script>

<style scoped>
.chapter-manager {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.chapter-manager-title {
  color: #1890ff;
  margin-bottom: 20px;
  font-size: 18px;
  font-weight: bold;
}

.chapter-item {
  margin-bottom: 20px;
  padding: 15px;
  background: #f5f7fa;
  border-radius: 6px;
}

.chapter-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #e4e7ed;
}

.chapter-info {
  display: flex;
  align-items: center;
  gap: 10px;
  flex: 1;
}

.chapter-name-input {
  width: 300px;
}

.chapter-duration {
  color: #606266;
  font-size: 14px;
}

.chapter-actions {
  display: flex;
  gap: 8px;
}

.sections-container {
  margin-left: 20px;
}

.section-item {
  margin-bottom: 15px;
  padding: 15px;
  background: #fff;
  border-radius: 4px;
  border: 1px solid #ebeef5;
}

.section-info {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
  margin-bottom: 10px;
}

.section-type-select {
  width: 100px;
}

.section-name-input {
  flex: 1;
  min-width: 200px;
}

.section-video,
.section-document {
  display: flex;
  align-items: center;
  gap: 10px;
}

.duration-input {
  width: 120px;
}

.media-preview {
  width: 100%;
  margin-top: 10px;
  padding: 10px;
  background: #fafafa;
  border-radius: 4px;
}

.preview-video {
  width: 100%;
  max-width: 400px;
  height: auto;
}

.section-actions {
  display: flex;
  gap: 8px;
  justify-content: flex-end;
}

.add-chapter-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px dashed #e4e7ed;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .chapter-header,
  .section-info {
    flex-direction: column;
    align-items: stretch;
  }
  
  .chapter-name-input {
    width: 100%;
  }
  
  .section-actions {
    justify-content: center;
  }
}
</style>